<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\AfterSalesRequest;
use App\Models\AfterSalesLogistic;
use App\Models\SystemSetting;
use Carbon\Carbon;

class AutoConfirmExchangeDelivery extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'after-sales:auto-confirm-delivery {--days=7 : 超时天数，默认7天}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动确认换货商品送达（超时处理）';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // 从系统设置读取超时天数，如果命令行有指定则优先使用命令行参数
        $days = $this->option('days') ?: (int) SystemSetting::get('exchange_delivery_timeout_days', 7);
        $cutoffDate = Carbon::now()->subDays($days);
        
        $this->info("开始处理超过 {$days} 天未确认送达的换货申请...");
        
        // 查找需要自动确认的换货申请
        $requests = AfterSalesRequest::where('type', AfterSalesRequest::TYPE_EXCHANGE)
            ->where('status', AfterSalesRequest::STATUS_PROCESSING)
            ->where('extended_status', AfterSalesRequest::EXTENDED_STATUS_NEW_SENT)
            ->whereHas('logistics', function ($query) use ($cutoffDate) {
                $query->where('submitted_by', AfterSalesLogistic::SUBMITTED_BY_ADMIN)
                    ->where('type', AfterSalesLogistic::TYPE_EXCHANGE)
                    ->where('status', 'shipped')
                    ->where('sent_at', '<=', $cutoffDate);
            })
            ->get();
        
        $count = 0;
        
        foreach ($requests as $request) {
            try {
                // 自动确认送达
                $request->markNewDelivered();
                
                // 记录自动确认日志
                \Log::info('Auto confirmed exchange delivery', [
                    'request_id' => $request->id,
                    'order_number' => $request->order->order_number,
                    'user_id' => $request->user_id,
                    'auto_confirmed_at' => now(),
                    'days_overdue' => $days
                ]);
                
                $count++;
                $this->line("已自动确认售后申请 #{$request->id} 的换货送达");
                
            } catch (\Exception $e) {
                $this->error("处理售后申请 #{$request->id} 时出错: " . $e->getMessage());
            }
        }
        
        $this->info("处理完成，共自动确认了 {$count} 个换货申请");
        
        return Command::SUCCESS;
    }
}